package com.ziyia.jetpack;

import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;

import java.util.Date;

public class MainViewModel extends ViewModel {
    private MutableLiveData<Integer> mutableLiveData = new MutableLiveData<>();

    // Map
    private MutableLiveData<User> userMutableLiveData = new MutableLiveData<>();
    private LiveData<String> userName = Transformations.map(userMutableLiveData, new Function<User, String>() {
        @Override
        public String apply(User input) {
            return input.getName();
        }
    });

    // switchMap
    private MutableLiveData<String> userIdLiveData = new MediatorLiveData<>();
    private LiveData<User> user = Transformations.switchMap(userIdLiveData, new Function<String, LiveData<User>>() {
        @Override
        public LiveData<User> apply(String input) {
            return Repository.getUser(input);
        }
    });

    private MutableLiveData<String> refreshLiveData = new MediatorLiveData<>();
    private LiveData<String> refreshResult = Transformations.switchMap(refreshLiveData, new Function<String, LiveData<String>>() {
        @Override
        public LiveData<String> apply(String input) {
            return Repository.refresh();
        }
    });


    public void setUser(String userId) {
        userIdLiveData.setValue(userId);
    }

    public MainViewModel() {
    }

    public MainViewModel(Integer i) {
        mutableLiveData.setValue(i);
    }

    public void plusOne() {
        Integer value = mutableLiveData.getValue();
        Integer count = value == null ? 0 : value;
        mutableLiveData.setValue(value + 1);
    }

    public void clear() {
        mutableLiveData.setValue(0);
    }

    public MutableLiveData<Integer> getMutableLiveData() {
        return mutableLiveData;
    }

    public LiveData<User> getUser() {
        return user;
    }

    public void getUser(String userId) {
        userIdLiveData.setValue(userId);
    }

    public void refresh(String str) {
        refreshLiveData.setValue(refreshLiveData.getValue());
    }
    @Override
    public String toString() {
        return "MainViewModel{" +
                ", mutableLiveData=" + mutableLiveData +
                '}';
    }

    public LiveData<String> getRefreshResult() {
        return refreshResult;
    }
}
